import { genDefDate } from '../../utils/DateUtils';
import { genCloudFilePath } from '../../utils/CloudUtils';
const db = wx.cloud.database({
  throwOnNotFound: false
})
const _ = db.command
const app=getApp();
var util = require('../../utils/util.js');//导入实现时间获取

Page({
  data:{
    name:'',
    avatar:[],
    date:'',
    desc:'',
    imgList: [],
   // count:[1,2,3,4,5,6,7,8,9],
  },  

  bindKeyInput(e){
    const key = e.currentTarget.dataset.key;
    let data={};
    data[key] = e.detail.value;
    this.setData(data);
  },



  


  uploadImg(filePath) { // 调用wx.cloud.uploadFile上传文件
    return wx.cloud.uploadFile({
      cloudPath: genCloudFilePath(filePath),
      filePath: filePath
    })
  },
    
  ChooseImage() {
 
    wx.chooseImage({
      count: 9, 
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album','camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '操作确认',
      content: '确定要删除这张照片吗？',
      cancelText: '取消',
      confirmText: '删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  saveData(data) {
    wx.showLoading({
      title: '发布中'
    });
    const uploadTasks = data.imgList.map(item => this.uploadImg(item))
    Promise.all(uploadTasks).then(result => {
      console.log(result);
      const imgList = result.map(img => (img.fileID));
      data.imgList = imgList;
      console.log(data);
      const db = wx.cloud.database();
      // data.geo = db.Geo.Point(data.location.longitude, data.location.latitude);
      db.collection('issuesList').add({
        data: data
      }).then(result => {
        console.log('保存成功', result)
        wx.hideLoading()
        wx.showToast({
          title: '发布成功',
          duration: 2000
        })
    
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/community/community',
          })
        }, 2000);
      }).catch(() => {
        wx.hideLoading()
        wx.showToast({
          title: '发布失败',
          icon: 'error'
        })
      })

    }).catch(() => {
      wx.hideLoading()
      wx.showToast({
        title: '上传图片错误',
        icon: 'error'
      })
    })
  },
  

  publish() {
    console.log("tapPublish");
    // if (this.checkLogin() == false) {
    //   return;
    // }
    let data = {};
    let errorMsg = "";
    data.desc=this.data.desc;
    data.imgList = this.data.imgList;
    data.name=this.data.name;
    data.avatar = this.data.avatar;
    data.date=this.data.date;
   

    if (data.imgList.length < 1) {
      errorMsg = '至少上传一张照片';
    }
    if (data.desc == "") {
      errorMsg = '请完善动态发布信息';
    }
  
    if (errorMsg) {
      wx.showToast({
        title: errorMsg,
        icon: 'none'
      })
      return;
    }

    this.saveData(data);

     //查找用户的_id，通过id更新发表的动态数据,userInfo的postedcomment+1
     wx.cloud.callFunction({ //调用云函数获取openid
      name: "getOpenId",
      complete: res => {
        db.collection("userInfo").where({
          _openid: res.result.openid //进行筛选
        }).get({

          success: res => {
            console.log("该用户的_id为：", res.data[0]._id)
            db.collection('userInfo').doc(res.data[0]._id).update({
              data: {
                postedcomment: _.inc(+1)
              }
            })
            console.log("更新成功，动态+1")
          },
          fail: res => {
            console.log("获取用户_id信息失败", res)
            return;
          }
        })
      }
    });

  },
  onLoad: function(options) {//获取当前日期
  var DATE = util.formatTime(new Date());
  this.setData({
    date: DATE,
    });
    var that = this;
    wx.getUserInfo({   // 获取用户信息
      success: function (res) {
        console.log(res);
        that.setData({
          avatar: res.userInfo.avatarUrl,
          name: res.userInfo.nickName,
        })
      }
    })
  },

})